package leetcode.code1396;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UndergroundSystem3 {

	Map<Integer, Integer> checkIn1;
	Map<Integer, String> checkIn2;
	Map<String, Map<String, Integer>> totals;
	Map<String, Map<String, Integer>> sizes;

	public UndergroundSystem3() {
		checkIn1 = new HashMap<>();
		checkIn2 = new HashMap<>();
		totals = new HashMap<>();
		sizes = new HashMap<>();
	}

	public void checkIn(int id, String stationName, int t) {
		checkIn1.put(id, t);
		checkIn2.put(id, stationName);
	}

	public void checkOut(int id, String stationName, int t) {
		int intime = checkIn1.get(id);
		String intStation = checkIn2.get(id);
		int sum = totals.computeIfAbsent(intStation, key -> new HashMap<>()).computeIfAbsent(stationName, k -> 0);
		sum += t - intime;
		totals.get(intStation).put(stationName, sum);
		int size = sizes.computeIfAbsent(intStation, key -> new HashMap<>()).computeIfAbsent(stationName, k -> 0);
		sizes.get(intStation).put(stationName, ++size);
	}

	public double getAverageTime(String startStation, String endStation) {
		double total = totals.get(startStation).get(endStation);
		double size = sizes.get(startStation).get(endStation);
		return total / size;
	}
}
